<!DOCTYPE html>
<html lang="en">

<head>
<title>简学-聊天室</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="Thu, 19 Nov 1900 08:52:00 GMT">
<?
	  include("/inc/header.html") {}
?>
</head>
<style>
button{
	display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid transparent;
    border-radius: 4px;
}
button:HOVER {
	background-color: #ccc;
}
button:active{
    transform:scale(0.95);
    -ms-transform:rotate(0.95); 	/* IE 9 */
    -moz-transform:rotate(0.95); 	/* Firefox */
    -webkit-transform:rotate(0.95); /* Safari 和 Chrome */
    -o-transform:rotate(0.95); 	/* Opera */
}
#message span{
	margin-left: 10px;
}

</style>
<body>
	<div id="message" style="overflow: auto;border-top: 1px solid #03a9f4;border-bottom: 1px solid #03a9f4;border-radius: 20px;"></div>
	<div style="position: fixed;bottom: 0;width: 99%;" id="bottom">
   <!-- <hr style="border-color: #71baf1;"/> -->
   	<div style="width:100%;text-align:right;">
   	<!-- 
	<button onclick="openWebSocket()">上线</button>
    <button onclick="closeWebSocket()">下线</button>
     -->
     <button onclick="clearAll()">清屏</button>
     在线总人数：<span id="onlineNumber"></span>
    </div>
   <hr style="border-color: #71baf1;"/>
   <div>
 	<textarea rows="6" id="text" style="width: 100%" onkeydown="keySend(event);"></textarea>
    <div style="width:100%;text-align:right;"><button onclick="send()">发送消息   (换行:CTRLE+ENTER)</button></div>
    <hr/>
    
    <hr style="border-color: #71baf1;"/>
   </div>
   </div>
   <input type="hidden" id="id" value="${id}">
 </body>
<script>
var jihuo;
var hiddenProperty = 'hidden' in document ? 'hidden' :    
    'webkitHidden' in document ? 'webkitHidden' :    
    'mozHidden' in document ? 'mozHidden' :    
    null;
var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
var onVisibilityChange = function(){
    if (!document[hiddenProperty]) {    
        //console.log('页面激活');
        jihuo=true;
    }else{
        jihuo=false;
        //console.log('页面非激活');
    }
}
document.addEventListener(visibilityChangeEvent, onVisibilityChange);

function clearAll(){
	$("#message").html("");
}

	var websocket = null;
	window.onload=function(){
		setMessageHeight();
		openWebSocket()
	};
	window.onresize = function(){
		setMessageHeight();
	}
	function setMessageHeight(){
		var divBottom = document.getElementById('bottom').clientHeight;
		var divBody = document.documentElement.clientHeight;
		document.getElementById('message').style.height=(divBody-divBottom-18)+"px";
		var divscll = document.getElementById('message');
  		divscll.scrollTop = divscll.scrollHeight;
	}

	function openWebSocket(){
		if(websocket!=null){
			return;
		}  
	    //判断当前浏览器是否支持WebSocket
	    if ('WebSocket' in window) {
	    	//此端口8081是把此maven-web项目加入到tomcat容器中设置的HTTP/1.1对应的端口，JavaWebSocket
	    	//是对应的项目名称，websocket是websocket 服务端代码 @ServerEndpoint("/websocket")。
	        //websocket = new WebSocket("ws://47.95.197.157:8088/jianxue/websocket/"+$("#id").val());
	        websocket = new WebSocket("ws://47.95.197.157:7397/websocket/"+$("#id").val());
	    }
	    else {
	        alert('当前浏览器 Not support websocket')
	    }
	    //连接发生错误的回调方法
	    websocket.onerror = function () {
	        //setMessageInnerHTML("{WebSocket连接发生错误}");
	        alert("WebSocket连接发生错误")
	    };
	
	    //连接成功建立的回调方法
	    websocket.onopen = function () {
	        //setMessageInnerHTML("WebSocket连接成功");
	    }
	
	    //接收到消息的回调方法
	    websocket.onmessage = function (event) {
	        setMessageInnerHTML(event.data);
	    }
	
	    //连接关闭的回调方法
	    websocket.onclose = function () {
	       // setMessageInnerHTML("<span style=\"color:blue;\">您已下线</span>");
	        websocket=null;
	    }
	
	}
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
	

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
    	var obj = JSON.parse(innerHTML); 
    	var onlineNumber = obj.onlineNumber;
    	$("#onlineNumber").html(onlineNumber);
    	var usrname = obj.username;
    	var content=obj.content;
    	if(content!=undefined){
	    	var text = '';
	    	if(usrname=="老师"){
	    		text = "<span style=\"color: #ff0000;font-weight: bold;\">"+usrname+"&nbsp;&nbsp;"+new Date().Format("HH:mm:ss")+"</span></br>";
	    	}else{
	    		text = "<span style=\"color: #0e08ff;font-weight: bold;\">"+usrname+"&nbsp;&nbsp;"+new Date().Format("HH:mm:ss")+"</span></br>";
	    	}
	    	text+="&nbsp;&nbsp;&nbsp;&nbsp;";
	    	text+=content.replace(/ /g, "&nbsp;").replace(/\n/g, "<br/>&nbsp;&nbsp;&nbsp;&nbsp;").replace(/∷≡∷≡∷/g,"<br/>&nbsp;&nbsp;&nbsp;&nbsp;");
	        //document.getElementById('message').innerHTML +="<span style=\"font-family: cursive;\">"+ text+"</span>" + '<br/>';
	        
	        var nScrollHight =  document.getElementById('message').scrollHeight;
	        var nScrollTop =  document.getElementById('message').scrollTop;
	        var nDivHight=document.getElementById('message').offsetHeight;
		     if(usrname=="老师"){
		     	document.getElementById('message').innerHTML +="<span style=\"font-family: cursive;font-size: 30px;\">"+ text+"</span>" + '<br/>';
		     }else{
		     	document.getElementById('message').innerHTML +="<span style=\"font-family: cursive;font-size: 25px;\">"+ text+"</span>" + '<br/>';
		     }
    	}
     
	    if(nScrollTop + nDivHight >= nScrollHight){
	    	//console.log("到底了");
	    	var divscll = document.getElementById('message');
  			divscll.scrollTop = divscll.scrollHeight;
	    }
	    onVisibilityChange();
	    if(!jihuo){
			clearTollingTitleText("您有新短信息，请及时查看！");
	    }else{
	    	clearTollingTitleText();
	    }
    }
    
    //关闭WebSocket连接
    function closeWebSocket() {
    	if(websocket!=null){
    		 websocket.close();
    	}
       
    }

    //发送消息
    function send() {
    	if(saveThis()){
	        var message =document.getElementById('text').value;
	        message='{"username":"老师","content":"'+message.replace("\"","\\\"").replace(/\n/g,'∷≡∷≡∷')+'"}';
	        websocket.send(message);
    	}
    }
	document.onkeydown=function(event){
		var e = event || window.event || arguments.callee.caller.arguments[0];
		if(e && e.keyCode==13 && !event.ctrlKey){ // 按 enter
			event.preventDefault();
			if(saveThis()){
				if(websocket!=null){
					send();
					document.getElementById("text").value='';
				}
			}
		}
	}
	
	function keySend(event) {
		if (event.ctrlKey && event.keyCode == 13) {
			var len = getCursorPos(document.getElementById("text"))
			var text = document.getElementById("text").value;
			text = text.substring(0,len)+"\n"+text.substring(len,text.length);
			document.getElementById("text").value=text;
			setCursorPosition(document.getElementById("text"),len+1);
		}
	}

	function getCursorPos(pTextArea) {
		var cursurPosition = -1;
		if (pTextArea.selectionStart) { //非IE浏览器
			cursurPosition = pTextArea.selectionStart;
		} else { //IE
			var range = document.selection.createRange();
			range.moveStart("character", -pTextArea.value.length);
			cursurPosition = range.text.length;
		}
		return cursurPosition;
	}
	function setCursorPosition(elem, index) {
		var val = elem.value
		var len = val.length

		// 超过文本长度直接返回
		if (len < index) return
		setTimeout(function() {
			elem.focus()
			if (elem.setSelectionRange) { // 标准浏览器
				elem.setSelectionRange(index, index)
			} else { // IE9-
				var range = elem.createTextRange()
				range.moveStart("character", -len)
				range.moveEnd("character", -len)
				range.moveStart("character", index)
				range.moveEnd("character", 0)
				range.select()
			}
		}, 10)
	}



	String.prototype.trim = function() {
		return this.replace(/(^\s*)|(\s*$)/g, "");
	}
function saveThis(){
	var subject = document.getElementById("text").value;
	var fatieContent = document.getElementById("text").value;
     if(subject.trim() ==''){
   		return false;
 	}else if(fatieContent==''){
 		return false;
	}else{
		return true;
	}
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}



var timerID = null

 function rollingTitleText(titleText){  
     timerID = setTimeout(() => {
       document.title = titleText.substring(1, titleText.length) + titleText.substring(0,1)  //截取字符重新赋值给title
       titleText = document.title.substring(0, titleText.length)
       rollingTitleText(titleText)
     }, 1000)
 }
// 清除document.title 滚动
function clearTollingTitleText(){
    document.title = "简学-聊天室"
    clearTimeout(timerID) 
}
</script>
</html>